﻿#region Copyrights Notice
//©2010 Microsoft Corporation. All rights reserved.
#endregion

#region usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.InformationSecurity.CISF.SecurityPortal.Business.Entities;
using Microsoft.InformationSecurity.CISF.SecurityPortal.Data;
#endregion

namespace Microsoft.InformationSecurity.CISF.SecurityPortal.Business.WidgetFacade
{
    public class WidgetFacade
    {
        #region Private Operations
        private string _UserName;
        public WidgetFacade(string userName)
        {
            this._UserName = userName;
        }
        private WidgetInstance CopyWidgetInstance(Dictionary<string, string> tmpWI)
        {
            WidgetInstance rw = new WidgetInstance();
            rw.WidgetInstanceId = Int32.Parse(tmpWI["WidgetInstanceId"]);
            rw.WidgetId = Int32.Parse(tmpWI["WidgetId"]);
            rw.UserId = Int32.Parse(tmpWI["UserId"]);
            rw.TableColPos = int.Parse(tmpWI["ColumnNo"]);
            rw.TableRowPos = int.Parse(tmpWI["OrderNo"]);
            rw.SetExpanded(int.Parse(tmpWI["Expanded"]));
            rw.Caption = tmpWI["Title"];
            rw.State = tmpWI["State"];
            rw.VersionNo = int.Parse(tmpWI["VersionNo"]);
            rw.Widget.WidgetId = Int32.Parse(tmpWI["WidgetId"]);
            rw.Widget.Url = tmpWI["Url"];

            return rw;
        }
        private Widget CopyWidget(Dictionary<string, string> tmpW)
        {
            Widget w = new Widget();
            w.WidgetId = Int32.Parse(tmpW["WidgetId"]);
            w.Name = tmpW["Name"];
            w.Url = tmpW["Url"];
            w.Description = tmpW["Description"];
            w.CreatedDate = DateTime.Parse(tmpW["CreatedDate"]);
            w.LastUpdate = DateTime.Parse(tmpW["LastUpdate"]);
            w.VersionNo = int.Parse(tmpW["VersionNo"]);
            w.IsDefault = bool.Parse(tmpW["IsDefault"]);
            w.DefaultState = tmpW["DefaultState"];
            w.Icon = tmpW["Icon"];
            w.OrderNo = int.Parse(tmpW["OrderNo"]);

            return w;
        }
        private WidgetSetup RearrangeUserWidgets(WidgetSetup _Setup)
        {
            WidgetDataAccess dbHelper = new WidgetDataAccess();
            //Reorder the new list.
            int row = 0, col = 0;
            int widgetsPerColumn = (int)Math.Ceiling((float)_Setup.WidgetInstances.Count / 3.0);
            int widgetsPerRow = 3;

            foreach (WidgetInstance w in _Setup.WidgetInstances)
            {
                w.TableColPos = col;
                w.TableRowPos = row;

                col++;
                if (col >= widgetsPerRow)
                {
                    col = 0;
                    row++;
                }
                dbHelper.UpdateWidget(_UserName, w.WidgetId, w.TableRowPos, w.TableColPos, w.Expanded, w.Caption, w.State, w.VersionNo);
            }

            return _Setup;
        }

        private WidgetSetup NewUserVisit()
        {
            using (new AuditTrail(this._UserName, "New user visit"))
            {
                var WidgetSetup = new WidgetSetup();

                WidgetDataAccess dbHelper = new WidgetDataAccess();
                //Create a new user
                int UserId = dbHelper.GetUserId(this._UserName);
                //Create default widgets for new user.
                bool retStatus = dbHelper.CreateDefaultWidgets(this._UserName);
                //get list of default widgets just created.
                List<Dictionary<string, string>> WidgetInstances = dbHelper.GetUserWidgetInstances(this._UserName);

                //Construct WidgetSetup...
                foreach (Dictionary<string, string> tmpWI in WidgetInstances)
                {
                    WidgetInstance rw = CopyWidgetInstance(tmpWI);

                    //Add rw to WidgetSetup
                    WidgetSetup.WidgetInstances.Add(rw);
                }
                return WidgetSetup;
            }
        }
        private WidgetSetup LoadUserSetup()
        {
            using (new AuditTrail(this._UserName, "Existing user revisit"))
            {
                var WidgetSetup = new WidgetSetup();

                WidgetDataAccess dbHelper = new WidgetDataAccess();
                //get list of default widgets for this user.
                List<Dictionary<string, string>> WidgetInstances = dbHelper.GetUserWidgetInstances(this._UserName);

                //Construct WidgetSetup...
                foreach (Dictionary<string, string> tmpWI in WidgetInstances)
                {
                    WidgetInstance rw = CopyWidgetInstance(tmpWI);

                    //Add rw to WidgetSetup
                    WidgetSetup.WidgetInstances.Add(rw);
                }

                return WidgetSetup;
            }
        }

        #endregion

        #region SOA Operations

        public Boolean IsUserRegistered()
        {
            using (new AuditTrail(this._UserName, "Check if user is registered"))
            {
                WidgetDataAccess dbHelper = new WidgetDataAccess();
                //Create a new user
                Boolean res = dbHelper.IsUserRegistered(this._UserName);
                return res;
            }
        }

        public WidgetSetup LoadWidgetSetup()
        {
            if (!IsUserRegistered())
            {
                return NewUserVisit();
            }
            else
            {
                return LoadUserSetup();
            }
        }

        public WidgetSetup GetWidgetSetup() //Get user setup without auditTrail
        {
            var WidgetSetup = new WidgetSetup();

            WidgetDataAccess dbHelper = new WidgetDataAccess();
            //get list of default widgets for this user.
            List<Dictionary<string, string>> WidgetInstances = dbHelper.GetUserWidgetInstances(this._UserName);

            //Construct WidgetSetup...
            foreach (Dictionary<string, string> tmpWI in WidgetInstances)
            {
                WidgetInstance rw = CopyWidgetInstance(tmpWI);

                //Add rw to WidgetSetup
                WidgetSetup.WidgetInstances.Add(rw);
            }

            return WidgetSetup;
        }

        public WidgetSetup ResetWidgetSetup()
        {
            using (new AuditTrail(this._UserName, "Resetting User Widget Setup"))
            {
                var WidgetSetup = new WidgetSetup();

                WidgetDataAccess dbHelper = new WidgetDataAccess();

                //Create default widgets for new user.
                bool retStatus = dbHelper.CreateDefaultWidgets(this._UserName);
                //get list of default widgets just created.
                List<Dictionary<string, string>> WidgetInstances = dbHelper.GetUserWidgetInstances(this._UserName);

                //Construct WidgetSetup...
                foreach (Dictionary<string, string> tmpWI in WidgetInstances)
                {
                    WidgetInstance rw = CopyWidgetInstance(tmpWI);

                    //Add rw to WidgetSetup
                    WidgetSetup.WidgetInstances.Add(rw);
                }
                return WidgetSetup;
            }
        }

        public WidgetSetup UpdateWidgetSetup(WidgetSetup _Setup, WidgetSetup _newSetup)
        {
            using (new AuditTrail(this._UserName, "Update user setup"))
            {
                WidgetDataAccess dbHelper = new WidgetDataAccess();

                //find and remove unslected widgets.
                for (int i = 0; i < _Setup.WidgetInstances.Count; i++)
                {
                    bool itemFound = false;
                    foreach (WidgetInstance w1 in _newSetup.WidgetInstances)
                    {
                        if (w1.WidgetId == _Setup.WidgetInstances.ElementAt<WidgetInstance>(i).WidgetId)
                        {
                            itemFound = true;
                            break;
                        }
                    }
                    if (itemFound == false) //not found, remove.
                    {
                        bool res = dbHelper.DeleteWidget(this._UserName, _Setup.WidgetInstances.ElementAt<WidgetInstance>(i).WidgetId);
                        if (res == false) //success
                        {
                            _Setup.WidgetInstances.Remove(_Setup.WidgetInstances.ElementAt<WidgetInstance>(i));
                            i--;
                        }
                    }
                }

                //Find new; add.
                for (int i = 0; i < _newSetup.WidgetInstances.Count; i++)
                {
                    bool itemFound = false;
                    foreach (WidgetInstance w1 in _Setup.WidgetInstances)
                    {
                        if (w1.WidgetId == _newSetup.WidgetInstances.ElementAt<WidgetInstance>(i).WidgetId)
                        {
                            itemFound = true;
                            break;
                        }
                    }
                    if (itemFound == false) //not found, add.
                    {
                        WidgetInstance w = _newSetup.WidgetInstances.ElementAt<WidgetInstance>(i);

                        w.WidgetId = w.Widget.WidgetId;
                        w.SetExpanded(1);
                        w.Caption = w.Widget.Name;
                        w.VersionNo = w.Widget.VersionNo;
                        w.State = w.Widget.DefaultState;

                        bool res = dbHelper.AddWidget(_UserName, w.WidgetId, w.TableRowPos, w.TableColPos, w.Expanded, w.Caption, w.State, w.VersionNo);
                        if (res == false) //success
                        {
                            _Setup.WidgetInstances.Add(w);
                        }
                    }
                }

                _Setup = RearrangeUserWidgets(_Setup);

                return GetWidgetSetup();
            }
        }

        public List<Widget> GetWidgetList()
        {
            using (new AuditTrail(this._UserName, "Get Widget List"))
            {
                List<Widget> Widgets = new List<Widget>();
                WidgetDataAccess dbHelper = new WidgetDataAccess();
                //get list of widgets.
                List<Dictionary<string, string>> retWidgets = dbHelper.GetWidgetList();

                //Construct WidgetSetup...
                foreach (Dictionary<string, string> Wiget in retWidgets)
                {
                    Widget w = CopyWidget(Wiget);

                    //Add rw to WidgetSetup
                    Widgets.Add(w);
                }
                return Widgets;
            }
        }

        public Boolean MinimizeWidget(Int32 WidgetId)
        {
            using (new AuditTrail(this._UserName, string.Format("WidgetId : " + WidgetId.ToString() + " ; UserAction: Minimize Widget")))
            {
                WidgetDataAccess dbHelper = new WidgetDataAccess();
                Boolean res = dbHelper.ModifyWidgetSize(_UserName, WidgetId, 0);
                return res;
            }
        }
        public Boolean MaximizeWidget(Int32 WidgetId)
        {
            using (new AuditTrail(this._UserName, string.Format("WidgetId : " + WidgetId.ToString() + " ; UserAction: Maximize Widget")))
            {
                WidgetDataAccess dbHelper = new WidgetDataAccess();
                Boolean res = dbHelper.ModifyWidgetSize(_UserName, WidgetId, 1);
                return res;
            }
        }
        public Boolean FullScreenWidget(Int32 WidgetId)
        {
            using (new AuditTrail(this._UserName, string.Format("WidgetId : " + WidgetId.ToString() + " ; UserAction: MaximizeToFullScreen Widget")))
            {
                WidgetDataAccess dbHelper = new WidgetDataAccess();
                Boolean res = dbHelper.ModifyWidgetSize(_UserName, WidgetId, 2);
                return res;
            }
        }
        public Boolean UpdateWidgetState(Int32 WidgetId, string State)
        {
            using (new AuditTrail(this._UserName, string.Format("WidgetId : " + WidgetId.ToString() + " ; UserAction: Update Widget State")))
            {
                WidgetDataAccess dbHelper = new WidgetDataAccess();
                Boolean res = dbHelper.SaveWidgetState(_UserName, WidgetId, State);
                return res;
            }
        }
        public Boolean DeleteWidget(Int32 WidgetId)
        {
            using (new AuditTrail(this._UserName, string.Format("WidgetId : " + WidgetId.ToString() + " ; UserAction: Delete Widget")))
            {
                WidgetDataAccess dbHelper = new WidgetDataAccess();
                Boolean res = dbHelper.DeleteWidget(this._UserName, WidgetId);

                if (res == true) //Error
                    return true;

                var WidgetSetup = new WidgetSetup();
                //get list of widgets for this user.
                List<Dictionary<string, string>> WidgetInstances = dbHelper.GetUserWidgetInstances(this._UserName);

                //Construct WidgetSetup...
                foreach (Dictionary<string, string> tmpWI in WidgetInstances)
                {
                    WidgetInstance rw = CopyWidgetInstance(tmpWI);

                    //Add rw to WidgetSetup
                    WidgetSetup.WidgetInstances.Add(rw);
                }


                //rearrange the widgets.
                WidgetSetup = RearrangeUserWidgets(WidgetSetup);

                if (WidgetSetup == null) //Error
                    return true;
                else
                    return false;
            }
        }

        #endregion
    }
}
